package com.shiyi.localresolver;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 自定义Locale解析器
 * @author wangzhanshuai
 * @date 2021/1/23 6:29 下午
 * @since 1.0
 */
public class MyLocalResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String localStr = request.getParameter("locale");
        System.out.println(localStr);
        if(StringUtils.hasText(localStr)) {
            String[] split = localStr.split("_");
            if(split.length == 2) {
                return new Locale(split[0], split[1]);
            }
        }
        return request.getLocale();
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException(
                "Cannot change HTTP accept header - use a different locale resolution strategy");
    }
}
